/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import me.zhengjie.modules.biz.domain.Announcement;
import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.domain.Vidicon;
import me.zhengjie.modules.biz.domain.VidiconRecord;
import me.zhengjie.modules.biz.repository.LabRepository;
import me.zhengjie.modules.biz.repository.VidiconRepository;
import me.zhengjie.modules.biz.service.dto.CabinetDto;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.VidiconRecordRepository;
import me.zhengjie.modules.biz.service.VidiconRecordService;
import me.zhengjie.modules.biz.service.dto.VidiconRecordDto;
import me.zhengjie.modules.biz.service.dto.VidiconRecordQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.VidiconRecordMapper;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64;
import java.util.*;
import java.io.IOException;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class VidiconRecordServiceImpl implements VidiconRecordService {

    private final VidiconRecordRepository vidiconRecordRepository;
    private final VidiconRecordMapper vidiconRecordMapper;
    private final LabRepository labRepository;

    private final VidiconRepository vidiconRepository;


    @Override
    public List<VidiconRecordDto> queryAll(VidiconRecordQueryCriteria criteria){
        Specification<VidiconRecord> specification =  (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("name"), criteria.getName()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"),  criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("type"), criteria.getType()));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<VidiconRecord> vidiconRecordList = vidiconRecordRepository.findAll(specification);
        List<VidiconRecordDto> vidiconRecordDtoList = vidiconRecordMapper.toDto(vidiconRecordList);
        for (VidiconRecordDto vidiconRecordDto : vidiconRecordDtoList) {
            Lab lab = labRepository.findById(vidiconRecordDto.getLabId()).orElseGet(Lab::new);
            vidiconRecordDto.setLabName(lab.getName());
        }
        return vidiconRecordDtoList;
    }

    @Override
    @Transactional
    public VidiconRecordDto findById(Integer id) {
        VidiconRecord vidiconRecord = vidiconRecordRepository.findById(id).orElseGet(VidiconRecord::new);
        ValidationUtil.isNull(vidiconRecord.getId(),"VidiconRecord","id",id);
        return vidiconRecordMapper.toDto(vidiconRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VidiconRecordDto create(VidiconRecord resources) {
        Vidicon vidicon = vidiconRepository.findById(resources.getVidiconId()).orElseGet(Vidicon::new);
        resources.setName(vidicon.getName());
        return vidiconRecordMapper.toDto(vidiconRecordRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(VidiconRecord resources) {
        VidiconRecord vidiconRecord = vidiconRecordRepository.findById(resources.getId()).orElseGet(VidiconRecord::new);
        ValidationUtil.isNull( vidiconRecord.getId(),"VidiconRecord","id",resources.getId());
        vidiconRecord.copy(resources);
        vidiconRecordRepository.save(vidiconRecord);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            vidiconRecordRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<VidiconRecordDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (VidiconRecordDto vidiconRecord : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", vidiconRecord.getName());
            map.put("实验室", vidiconRecord.getLabName());
            map.put("下载地址", vidiconRecord.getSite());
            map.put("记录时间", vidiconRecord.getCreatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Map<String, Object> queryVideo(VidiconRecordQueryCriteria criteria, Pageable pageable) {
        Specification<VidiconRecord> specification = (Specification<VidiconRecord>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("name"), criteria.getName()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"),  criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
//            if (criteria.getStartTime() != null && criteria.getEndTime() != null) {
//                Timestamp sTime = DateUtil.strToSqlDate(criteria.getStartTime());
//                Timestamp eTime = DateUtil.strToSqlDate(criteria.getEndTime());
//                predicates.add(criteriaBuilder.between(root.get("recordTime"), sTime, eTime));
//            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 1));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<VidiconRecord> page = vidiconRecordRepository.findAll(specification,pageable);
        Page<VidiconRecordDto> dto = page.map(vidiconRecordMapper::toDto);
        List<VidiconRecordDto> resultDto = dto.getContent();
        for (VidiconRecordDto vidiconRecordDto:resultDto) {
            Lab lab = labRepository.findById(vidiconRecordDto.getLabId()).orElseGet(Lab::new);
            vidiconRecordDto.setLabName(lab.getName());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public Map<String, Object> queryPicture(VidiconRecordQueryCriteria criteria, Pageable pageable) {
        Specification<VidiconRecord> specification = (Specification<VidiconRecord>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("name"), criteria.getName()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"),  criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
//            if (criteria.getStartTime() != null && criteria.getEndTime() != null) {
//                Timestamp sTime = DateUtil.strToSqlDate(criteria.getStartTime());
//                Timestamp eTime = DateUtil.strToSqlDate(criteria.getEndTime());
//                predicates.add(criteriaBuilder.between(root.get("recordTime"), sTime, eTime));
//            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 2));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<VidiconRecord> page = vidiconRecordRepository.findAll(specification,pageable);
        Page<VidiconRecordDto> dto = page.map(vidiconRecordMapper::toDto);
        List<VidiconRecordDto> resultDto = dto.getContent();
        for (VidiconRecordDto vidiconRecordDto:resultDto) {
            Lab lab = labRepository.findById(vidiconRecordDto.getLabId()).orElseGet(Lab::new);
            vidiconRecordDto.setLabName(lab.getName());
        }
        return PageUtil.toPage(dto);
    }

    @Override
    public List<VidiconRecordDto> queryPicture(VidiconRecordQueryCriteria criteria) {
        Specification<VidiconRecord> specification = (Specification<VidiconRecord>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("name"), criteria.getName()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"),  criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 2));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<VidiconRecord> vidiconRecordList = vidiconRecordRepository.findAll(specification);
        List<VidiconRecordDto> vidiconRecordDtoList = vidiconRecordMapper.toDto(vidiconRecordList);
        for (VidiconRecordDto vidiconRecordDto : vidiconRecordDtoList) {
            Lab lab = labRepository.findById(vidiconRecordDto.getLabId()).orElseGet(Lab::new);
            vidiconRecordDto.setLabName(lab.getName());
        }
        return vidiconRecordDtoList;
    }

    @Transactional(rollbackFor = Exception.class)
    public VidiconRecordDto analysisPhoto(String data) {
        JSONObject jsonObject = JSONUtil.parseObj(data);
        String photo = jsonObject.getStr("photo");
        String path = System.getProperty("java.io.tmpdir") + "/file/photo/".concat(IdUtil.randomUUID()).concat(".jpg");
        photo = photo.substring(photo.indexOf(",", 1) + 1, photo.length());
        byte[] b = Base64.decodeBase64(photo);
        // 处理数据
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }

        Vidicon vidicon = vidiconRepository.findById(Convert.toInt(jsonObject.getStr("vidiconId"))).orElseGet(Vidicon::new);
        VidiconRecord vidiconRecord = new VidiconRecord();
        vidiconRecord.setVidiconId(Convert.toInt(jsonObject.getStr("vidiconId")));
        vidiconRecord.setType(2);
        vidiconRecord.setSite(path);
        vidiconRecord.setName(vidicon.getName());
        vidiconRecord.setLabId(Convert.toInt(jsonObject.getStr("labId")));

        try {
            // 保存图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return vidiconRecordMapper.toDto(vidiconRecordRepository.save(vidiconRecord));

    }

    @Override
    public List<VidiconRecordDto> queryVideo(VidiconRecordQueryCriteria criteria) {
        Specification<VidiconRecord> specification =  (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<Predicate>();
            if (criteria.getLabId() != null) {
                predicates.add(criteriaBuilder.equal(root.get("labId"), criteria.getLabId()));
            }
            if (criteria.getName() != null) {
                predicates.add(criteriaBuilder.equal(root.get("name"), criteria.getName()));
            }
            if (criteria.getCreatedAt() != null) {
                predicates.add(criteriaBuilder.between(root.get("createdAt"),  criteria.getCreatedAt().get(0), criteria.getCreatedAt().get(1)));
            }
            predicates.add(criteriaBuilder.equal(root.get("type").as(Integer.class), 1));
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        List<VidiconRecord> vidiconRecordList = vidiconRecordRepository.findAll(specification);
        List<VidiconRecordDto> vidiconRecordDtoList = vidiconRecordMapper.toDto(vidiconRecordList);
        for (VidiconRecordDto vidiconRecordDto : vidiconRecordDtoList) {
            Lab lab = labRepository.findById(vidiconRecordDto.getLabId()).orElseGet(Lab::new);
            vidiconRecordDto.setLabName(lab.getName());
        }
        return vidiconRecordDtoList;
    }
}
